# -*- coding: utf-8 -*-
from application import app
from flask import request,g,jsonify

from common.models.Customer import  Customer
from common.libs.customer.CustomerLibs import CustomerLibs
import  re

'''
api认证
'''
@app.before_request
def before_request_api():
    api_ignore_urls = app.config['API_IGNORE_URLS']
    ignore_check_login_urls = app.config["IGNORE_CHECK_LOGIN_URLS"]
    path = request.path
    if '/api' not in path:
        return

    pattern = re.compile("%s" % "|".join(ignore_check_login_urls))
    if pattern.match(path):
        return

    customer_info = check_customer_login()
    g.customer_info = None
    if customer_info:
        g.customer_info = customer_info

    pattern = re.compile('%s' % "|".join( api_ignore_urls ))
    if pattern.match(path):
        return

    if not customer_info :
        resp = {'code': -100, 'msg': '请登录~', 'data': {}}
        return jsonify(resp)

    return


'''
判断用户是否已经登录
'''
def check_customer_login():
    auth_cookie = request.headers.get("token")

    if auth_cookie is None:
        return False

    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False

    try:
        customer_info = Customer.query.filter_by(id=auth_info[1]).first()
    except Exception:
        return False

    if customer_info is None:
        return False

    if auth_info[0] != CustomerLibs.geneAuthCode( customer_info ):
        return False

    if customer_info.status != 1:
        return False

    return customer_info